package com.github.pudding.config;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;

import static javax.servlet.ServletRegistration.Dynamic;

/**
 * @author Stephen
 * @since 2018/8/31
 */
public class WebInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) {

        System.out.println("开始加载spring容器");
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(WebConfig.class);
        //rootContext.setServletContext(servletContext);

        //启动spring容器
        servletContext.addListener(new ContextLoaderListener(rootContext));

        System.out.println("开始加载springmvc容器");
        AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext();
        webContext.register(MvcConfig.class);

        Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(webContext));
        servlet.addMapping("/*");
        servlet.setLoadOnStartup(1);
    }
}
